# Copyright 2008 Brooklyn Marathon Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

__author__ = 'r.yozzo (Ralph Yozzo)'

import cgi
import wsgiref.handlers
import os
import logging
import datetime

from google.appengine.ext.webapp import template

from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp

#from string import strip, rstrip, lstrip, replace
import re
from google.appengine.api import mail
from google.appengine.api import urlfetch


from google.appengine.api.labs import taskqueue

from google.appengine.api import xmpp
from google.appengine.ext.webapp import xmpp_handlers

def strip_tags(value):
  "Return the given HTML with all tags stripped."
  return re.sub(r'<[^>]*?>', '', value) 

def require_admin(handler_method):
  """Decorator that requires the requesting user to be an admin."""
  def decorate(myself, *args, **kwargs):
    if ('HTTP_X_APPENGINE_TASKNAME' in os.environ
        or users.is_current_user_admin()):
      handler_method(myself, *args, **kwargs)
    elif users.get_current_user() is None:
      myself.redirect(users.create_login_url(myself.request.url))
    else:
      myself.response.set_status(401)
  return decorate

################################################################################
# Send emails

class User(db.Model):
  campaign = db.StringProperty(required=True,default='campaign-name')
  subject = db.StringProperty(required=False, default='Subject')
  body_link = db.StringProperty(required=True, default='http://')
  to_link = db.StringProperty(required=True, default='http://')
  from_email = db.StringProperty(required=True, default='from@company.com')
  date_to_send = db.DateProperty(required=False, auto_now=True)
  owner = db.UserProperty()


class HourlyMailHandler(webapp.RequestHandler):
  def get(self):
    self.response.out.write('<html><body>')
    items = db.GqlQuery('SELECT * FROM EnQueueMailQueue2 ORDER BY date_to_send ASC LIMIT 10')

    for item in items:
      if item.date_to_send <= datetime.date.today():
        campaign = item.campaign
        urlto = item.tourl
        resultto = urlfetch.fetch(urlto)
        for line in resultto.content.splitlines():
          for email in line.split(","):
            if email:
              mailqueue = MailQueue2()
              mailqueue.campaign = campaign
              mailqueue.email = email
              mailqueue.date_to_send = item.date_to_send
              mailqueue.owner = users.get_current_user()
              mailqueue.put()
        taskqueue.add(
            url='/worker/email', params={ 'subject': item.subject, 'campaign': item.campaign, 'from': item.from_email , 'to': 'to', 'bodyurl': item.bodyurl, 'tourl': item.tourl })
        # put item in a archive log
        # item.delete()
    self.response.out.write('request completed.')
    self.response.out.write('</body></html>')

class EnQueuePrimerAdminMailHandler(webapp.RequestHandler):
  def get(self):
    self.response.out.write('<html><body>')
    tourl = None
    if self.request.get('tourl'):
      tourl = self.request.get('tourl')

    bodyurl = None
    if self.request.get('bodyurl'):
      bodyurl = self.request.get('bodyurl')
       
    campaign = None
    if self.request.get('campaign'):
      campaign = self.request.get('campaign')

    from_email = None
    if self.request.get('from_email'):
      from_email = self.request.get('from_email')

    subject = None
    if self.request.get('subject'):
      subject = self.request.get('subject')

    #campaign = 'tracking_crontest_1:%s' % datetime.datetime.today()
    # subject = 'Reminder: %s' % datetime.datetime.today()
    # urlto = self.request.get('tourl')
    # urlto = 'http://marketing.brooklynmarathon.com/static/to_test.txt'
    # urlto = 'http://move.brooklynmarathon.com/TEXTexportevententriespaged/%s' % key
    # resultto = urlfetch.fetch(urlto)
    # from1 = 'noreply@brooklynmarathon.com'
    # bodyurl = 'http://marketing.brooklynmarathon.com/static/letter_checkout3.html'
    # bodyurl = 'http://move.brooklynmarathon.com/REMINDERevententry/%s' % key
    date_to_send = None
    if self.request.get('date_to_send'):
      parts = self.request.get('date_to_send').split("-")
      if parts and len(parts) > 2:
        date_to_send = datetime.date(int(parts[0]), int(parts[1]), int(parts[2]))

    if tourl and date_to_send and from_email and campaign and subject and bodyurl:
      mailqueue = EnQueueMailQueue2(from_email = from_email, date_to_send = date_to_send)
      mailqueue.campaign = campaign
      mailqueue.tourl = tourl
      mailqueue.subject = subject
      mailqueue.bodyurl = bodyurl
      mailqueue.put()
      self.response.out.write('request queued.')
    else:
      self.response.out.write('parameters required: tourl and date_to_send and from_email and campaign and subject and bodyurl')
	   
    self.response.out.write('</body></html>')

class MailHandler(webapp.RequestHandler):
  def get(self):
    logging.debug('current_user: %s' % users.get_current_user())
    if not users.get_current_user():
      logging.debug('redirect: %s' % users.create_login_url(self.request.uri))
      self.redirect(users.create_login_url(self.request.uri))

    user = User()
    q = db.GqlQuery('SELECT * FROM User WHERE owner = :1 LIMIT 1', users.get_current_user())
    if q: 
      results = q.fetch(1)
      for result in results:
        user.campaign=result.campaign
        user.body_link=result.body_link
        user.to_link=result.to_link
        user.from_email=result.from_email


    if not user:
      self.redirect(users.create_login_url(self.request.path))
      return

    items = db.GqlQuery('SELECT * FROM MailQueue2 WHERE campaign = :1 and owner = :2 ORDER BY modified DESC LIMIT 10', user.campaign, users.get_current_user())

    #itemstosend = db.GqlQuery('SELECT * FROM MailQueue2 WHERE campaign = :1 and owner = :2 ORDER BY sent ASC LIMIT 10', user.campaign, users.get_current_user())
    itemstosend = db.GqlQuery('SELECT * FROM MailQueue2 WHERE campaign = :1 and owner = :2 and sent = :3 ORDER BY modified DESC LIMIT 10', user.campaign, users.get_current_user(), None)

    itemssent = db.GqlQuery('SELECT * FROM MailQueue2 WHERE owner = :1 ORDER BY modified DESC LIMIT 100', users.get_current_user())

    if user: 
      sign_out = users.CreateLogoutURL('/')

    template_values = {
      'user': users.get_current_user(),
      'save_user': user,
      'items': items,
      'itemstosend': itemstosend,
      'itemssent': itemssent,
      'sign_out': sign_out,
      }

    path = os.path.join(os.path.dirname(__file__), 'mail.html')
    self.response.out.write(template.render(path, template_values))

  def post(self):

    user = User()
    q = db.GqlQuery('SELECT * FROM User WHERE owner = :1 LIMIT 1', users.get_current_user())
    #logging.debug('q: %s' % q)
    if q: 
      results = q.fetch(1)
      # logging.debug('len(results) %s' % len(results))
      if results and len(results) > 0:
        # user = results.get(0)
        first = True
        for r in results:
          if first:
            user = r
            first = False
    if self.request.get('campaign'):
      user.campaign = self.request.get('campaign')
    if self.request.get('bodyurl'):
      user.body_link = self.request.get('bodyurl')
    if self.request.get('tourl'):
      user.to_link = self.request.get('tourl')
    if self.request.get('from'):
      user.from_email = self.request.get('from')
    user.owner = users.get_current_user()
    user.put()


    campaign = self.request.get('campaign')
    urlto = self.request.get('tourl')
    resultto = urlfetch.fetch(urlto)
    for line in resultto.content.splitlines():
      for email in line.split(","):
        if email:
          mailqueue = MailQueue2()
          mailqueue.campaign = campaign
          mailqueue.email = email
          mailqueue.owner = users.get_current_user()
          mailqueue.put()
	   
    taskqueue.add(
        url='/worker/email',
        #url='/worker/email?to=fedex1@gmail.com',
        #method='GET')
        #params={'from': 'checkout@brooklyncoop.org', 'to': users.get_current_user().email()})
	params={ 'subject': self.request.get('subject'), 'campaign': self.request.get('campaign'), 'from': self.request.get('from'), 'to': self.request.get('to'), 'bodyurl': self.request.get('bodyurl'), 'tourl': self.request.get('tourl')})
    self.redirect('/mail')


class EnQueuePrimerMailHandler(webapp.RequestHandler):
  def get(self):
    logging.debug('current_user: %s' % users.get_current_user())
    if not users.get_current_user():
      logging.debug('redirect: %s' % users.create_login_url(self.request.uri))
      self.redirect(users.create_login_url(self.request.uri))

    user = User()
    q = db.GqlQuery('SELECT * FROM User WHERE owner = :1 LIMIT 1', users.get_current_user())
    if q: 
      results = q.fetch(1)
      for result in results:
        user.campaign=result.campaign
        user.body_link=result.body_link
        user.to_link=result.to_link
        user.from_email=result.from_email
        user.date_to_send=result.date_to_send
        user.subject=result.subject


    if not user:
      self.redirect(users.create_login_url(self.request.path))
      return

    # items = db.GqlQuery('SELECT * FROM EnQueueMailQueue2 WHERE campaign = :1 and owner = :2 ORDER BY date_to_send ASC LIMIT 10', user.campaign, users.get_current_user())
    items = db.GqlQuery('SELECT * FROM EnQueueMailQueue2 WHERE owner = :1 ORDER BY date_to_send ASC LIMIT 10', users.get_current_user())

    if user: 
      sign_out = users.CreateLogoutURL('/')

    template_values = {
      'user': users.get_current_user(),
      'save_user': user,
      'items': items,
      'sign_out': sign_out,
      }

    path = os.path.join(os.path.dirname(__file__), 'enqueuemail.html')
    self.response.out.write(template.render(path, template_values))

  def post(self):

    user = User()
    q = db.GqlQuery('SELECT * FROM User WHERE owner = :1 LIMIT 1', users.get_current_user())
    #logging.debug('q: %s' % q)
    if q: 
      results = q.fetch(1)
      # logging.debug('len(results) %s' % len(results))
      if results and len(results) > 0:
        # user = results.get(0)
        first = True
        for r in results:
          if first:
            user = r
            first = False
    if self.request.get('subject'):
      user.subject = self.request.get('subject')
    if self.request.get('campaign'):
      user.campaign = self.request.get('campaign')
    if self.request.get('bodyurl'):
      user.body_link = self.request.get('bodyurl')
    if self.request.get('tourl'):
      user.to_link = self.request.get('tourl')
    if self.request.get('from'):
      user.from_email = self.request.get('from')
    logging.debug("date_to_send: %s" % self.request.get('date_to_send'))
    if self.request.get('date_to_send'):
      parts = self.request.get('date_to_send').split("-")
      if parts and len(parts) > 2:
        user.date_to_send = datetime.date(int(parts[0]), int(parts[1]), int(parts[2]))
    user.owner = users.get_current_user()
    user.put()

    mailqueue = EnQueueMailQueue2(from_email = user.from_email, date_to_send = user.date_to_send)
    mailqueue.campaign = user.campaign
    mailqueue.tourl = user.to_link
    mailqueue.owner = users.get_current_user()
    mailqueue.subject = user.subject
    mailqueue.bodyurl = user.body_link
    mailqueue.put()

    self.redirect('/enqueuemail')

class MailWorker(webapp.RequestHandler):
  # @require_admin
  def post(self):
    subject = 'Simple Online Event Registration for Race Directors'
    if self.request.get('subject'):
      subject = self.request.get('subject')      
    # logging.debug("XXX task send mail 1")
    # mail.send_mail( 'fedex1@gmail.com', self.request.get('to'), 'A special message to you', 'This is a test of the task queue')
    # url = 'http://wsxnyc.org/letter_checkout.html'
    url = self.request.get('bodyurl')
    logging.debug("URL: %s" % url)
    if url:
      resultfetch = urlfetch.fetch(url)
      logging.debug("URL: status_code %s" % resultfetch.status_code)
    # mail.send_mail( self.request.get('from'), self.request.get('to'), 'A special message to you', 'This is a test of the task queue')
    q = db.GqlQuery('SELECT * FROM MailQueue2 WHERE campaign = :1 ORDER BY sent ASC LIMIT 1', self.request.get('campaign'))
    if q: 
      results = q.fetch(1)
      for result in results:
	logging.debug("XXX task send mail TO: %s" % result.email)
	logging.debug("XXX task send mail TO: LEN: %s" % len(result.email))
        if not result.sent:
          if result.email:
            if len(result.email) > 0:
              try:
                mail.send_mail(sender=self.request.get('from'),
    	              # to=self.request.get('to'),
    	              to=result.email,
    		      bcc="fedex1@gmail.com",
    		      #subject="An order has been processed: %s" % result.shopping_cart_items_item_1_item_description ,
		      #subject="Simple Online Event Registration for Race Directors",
		      subject="%s - %s" % (subject, url) ,
    		      html=resultfetch.content,
  				                  body="""
%s

Details: 
%s
""" % (subject, url))
              except mail.InvalidEmailError, e:
                logging.error('send_mail error: %s', e)
    # logging.debug("XXX task send mail 2")
          result.sent = datetime.datetime.today()
	  result.put()

          taskqueue.add(
            url='/worker/email',
            #url='/worker/email?to=fedex1@gmail.com',
            #method='GET')
            #params={'from': 'checkout@brooklyncoop.org', 'to': users.get_current_user().email()})
	    params={ 'subject': subject, 'campaign': self.request.get('campaign'), 'from': self.request.get('from'), 'to': self.request.get('to'), 'bodyurl': self.request.get('bodyurl'), 'tourl': self.request.get('tourl')})

  # @require_admin
  def get(self):
    logging.debug("task send mail 1")
    # mail.send_mail( 'fedex1@gmail.com', self.request.get('to'), 'A special message to you', 'This is a test of the task queue')
    logging.debug("task send mail 2")

################################################################################
class EnQueueMailQueue2(db.Model):
  tourl = db.StringProperty()
  date_to_send = db.DateProperty(required=True)
  from_email = db.StringProperty(required=True)
  campaign = db.StringProperty()
  first = db.StringProperty()
  last = db.StringProperty()
  comments = db.TextProperty()
  sent = db.DateTimeProperty()
  created = db.DateTimeProperty(auto_now_add=True)
  modified = db.DateTimeProperty(auto_now=True)
  owner = db.UserProperty()
  subject = db.StringProperty()
  bodyurl = db.StringProperty()

class MailQueue2(db.Model):
  campaign = db.StringProperty()
  email = db.StringProperty()
  first = db.StringProperty()
  last = db.StringProperty()
  comments = db.TextProperty()
  sent = db.DateTimeProperty()
  created = db.DateTimeProperty(auto_now_add=True)
  modified = db.DateTimeProperty(auto_now=True)
  owner = db.UserProperty()
  subject = db.StringProperty()
  bodyurl = db.StringProperty()

class Greeting(db.Model):
	author = db.UserProperty()
	first = db.StringProperty(multiline=False)
	last = db.StringProperty(multiline=False)
	age = db.IntegerProperty(default = 0)
	gender = db.StringProperty(multiline=False)
	division = db.StringProperty(multiline=False)
	date = db.DateTimeProperty(auto_now_add=True)

class CheckoutLog(db.Model):
	uri = db.StringProperty()
	_type = db.StringProperty() 
	buyer_billing_address_address1 = db.StringProperty() 
	buyer_billing_address_address2 = db.StringProperty() 
	buyer_billing_address_city = db.StringProperty() 
	buyer_billing_address_company_name = db.StringProperty() 
	buyer_billing_address_contact_name = db.StringProperty() 
	buyer_billing_address_country_code = db.StringProperty() 
	buyer_billing_address_email = db.StringProperty() 
	buyer_billing_address_fax = db.StringProperty() 
	buyer_billing_address_phone = db.StringProperty() 
	buyer_billing_address_postal_code = db.StringProperty() 
	buyer_billing_address_region = db.StringProperty() 
	buyer_id = db.StringProperty() 
	buyer_marketing_preferences_email_allowed = db.StringProperty() 
	buyer_shipping_address_address1 = db.StringProperty() 
	buyer_shipping_address_address2 = db.StringProperty() 
	buyer_shipping_address_city = db.StringProperty() 
	buyer_shipping_address_company_name = db.StringProperty() 
	buyer_shipping_address_contact_name = db.StringProperty() 
	buyer_shipping_address_country_code = db.StringProperty() 
	buyer_shipping_address_email = db.StringProperty() 
	buyer_shipping_address_fax = db.StringProperty() 
	buyer_shipping_address_phone = db.StringProperty() 
	buyer_shipping_address_postal_code = db.StringProperty() 
	buyer_shipping_address_region = db.StringProperty() 
	financial_order_state = db.StringProperty() 
	fulfillment_order_state = db.StringProperty() 
	google_order_number = db.StringProperty() 
	latest_charge_amount = db.StringProperty() 
	latest_charge_amount_currency = db.StringProperty() 
	new_financial_order_state = db.StringProperty() 
	new_fulfillment_order_state = db.StringProperty() 
	order_adjustment_adjustment_total = db.StringProperty() 
	order_adjustment_adjustment_total_currency = db.StringProperty() 
	order_adjustment_total_tax = db.StringProperty() 
	order_adjustment_total_tax_currency = db.StringProperty() 
	order_total = db.StringProperty() 
	order_total_currency = db.StringProperty() 
	previous_financial_order_state = db.StringProperty() 
	previous_fulfillment_order_state = db.StringProperty() 
	risk_information_avs_response = db.StringProperty() 
	risk_information_billing_address_address1 = db.StringProperty() 
	risk_information_billing_address_address2 = db.StringProperty() 
	risk_information_billing_address_city = db.StringProperty() 
	risk_information_billing_address_company_name = db.StringProperty() 
	risk_information_billing_address_contact_name = db.StringProperty() 
	risk_information_billing_address_country_code = db.StringProperty() 
	risk_information_billing_address_email = db.StringProperty() 
	risk_information_billing_address_fax = db.StringProperty() 
	risk_information_billing_address_phone = db.StringProperty() 
	risk_information_billing_address_postal_code = db.StringProperty() 
	risk_information_billing_address_region = db.StringProperty() 
	risk_information_buyer_account_age = db.StringProperty() 
	risk_information_cvn_response = db.StringProperty() 
	risk_information_eligible_for_protection = db.StringProperty() 
	risk_information_ip_address = db.StringProperty() 
	risk_information_partial_cc_number = db.StringProperty() 
	shopping_cart_items = db.StringProperty() 
	shopping_cart_items_item_1_digital_content_description = db.StringProperty() 
	shopping_cart_items_item_1_item_description = db.StringProperty() 
	shopping_cart_items_item_1_item_name = db.StringProperty() 
	shopping_cart_items_item_1_quantity = db.StringProperty() 
	shopping_cart_items_item_1_unit_price = db.StringProperty() 
	shopping_cart_items_item_1_unit_price_currency = db.StringProperty() 
	timestamp = db.StringProperty() 
	total_charge_amount = db.StringProperty() 
	total_charge_amount_currency = db.StringProperty() 
	body = db.StringProperty()
	arguments = db.StringProperty()
	values = db.StringProperty()
	html = db.TextProperty()

class DumpTest(webapp.RequestHandler):
  def get(self):
    self.response.out.write('<html><body>')
    count = 0
    #entities = CheckoutLog.all().filter('_type =', 'order-state-change-notification').fetch(100)
    entities = CheckoutLog.all().fetch(100)
    while entities:
      for entity in entities:
        # Do something with entity
	count += 1
        self.response.out.write(entity._type)
        self.response.out.write(' - ')
        self.response.out.write(entity.key())
        self.response.out.write(' - ')
        self.response.out.write(entity.timestamp)
        self.response.out.write('<br/>')
      #entities = CheckoutLog.all().filter('_type =', 'order-state-change-notification').filter('__key__ >', entities[-1].key()).fetch(100)
      entities = CheckoutLog.all().filter('__key__ >', entities[-1].key()).fetch(100)
    self.response.out.write('count: %s<br/>' % count)
    self.response.out.write('</body></html>')


class Guestbook(webapp.RequestHandler):
  def post(self):
    greeting = Greeting()

    if users.get_current_user():
      greeting.author = users.get_current_user()

    greeting.first = self.request.get('first')
    greeting.last = self.request.get('last')
    greeting.age = int(self.request.get('age'))
    greeting.gender = self.request.get('gender')
    greeting.division = self.request.get('division')
    greeting.put()
    self.redirect('/')

class SendCheckout(webapp.RequestHandler):
  def get(self):
    urlto = 'http://wsxnyc.org/to_checkout.txt'
    resultto = urlfetch.fetch(urlto)

    url = 'http://wsxnyc.org/letter_checkout.html'
    resultfetch = urlfetch.fetch(url)

    for line in resultto.content.splitlines():
      for email in line.split(","):
        if len(email) > 0:
          mail.send_mail(sender="checkout@brooklyncoop.org",
    	              to=email,
    	              #to=toaddress,
    		      bcc="fedex1@gmail.com",
    		      #subject="An order has been processed: %s" % result.shopping_cart_items_item_1_item_description ,
		      subject="Simple Online Event Registration for Race Directors",
    		      html=resultfetch.content,
  				                  body="""
Simple Online Event Registration

Details: 
%s
""" % url)
      
    path = os.path.join(os.path.dirname(__file__), 'index.html')
    self.response.out.write(template.render(path, {}))

class Send(webapp.RequestHandler):
  def get(self):
    #urlto = 'http://wsxnyc.org/to2.txt'
    urlto = 'http://wsxnyc.org/to15.txt'
    resultto = urlfetch.fetch(urlto)

    url = 'http://wsxnyc.org/letter.html'
    resultfetch = urlfetch.fetch(url)

    for line in resultto.content.splitlines():
      for email in line.split(","):
	if len(email) > 0:
          mail.send_mail(sender="nyrrc-democracy-now@brooklyncoop.org",
    	              #to="fedex1@gmail.com",
    	              to=email,
    	              #to=toaddress,
    		      bcc="fedex1@gmail.com",
    		      #subject="A letter test: %s" % email ,
		      subject="A letter for NYRRC long time member: %s" % email,
    		      html=resultfetch.content,
  				                  body="""
A letter for NYRRC long time members

Details: 
%s
""" % url)
      

#     mail.send_mail(sender="nyrrc-democracy-now@brooklyncoop.org",
# 	              to="fedex1@gmail.com",
# 	              #to=toaddress,
# 		      bcc="fedex1@gmail.com",
# 		      #subject="An order has been processed: %s" % result.shopping_cart_items_item_1_item_description ,
# 		      subject="A letter for NYRRC long time members",
# 		      html=resultfetch.content,
# 				                  body="""
# A letter for NYRRC long time members
# 
# Details: 
# %s
# """ % url)


    path = os.path.join(os.path.dirname(__file__), 'index.html')
    self.response.out.write(template.render(path, {}))

class List(webapp.RequestHandler):
  @require_admin
  def get(self):
    #self.response.out.write(self.request.get('google_order_number'))
    #self.response.out.write('<br/>')
    self.response.out.write('<html><body>')
    if self.request.get('google_order_number'):
      q = db.GqlQuery('SELECT * FROM CheckoutLog WHERE google_order_number = :1 ORDER BY timestamp desc' , self.request.get('google_order_number'))
      #q = db.GqlQuery("SELECT * FROM CheckoutLog where google_order_number = ':1' order by timestamp desc" , self.request.get('google_order_number'))
      #q = db.GqlQuery("SELECT * FROM CheckoutLog WHERE google_order_number = '757965836430932' order by timestamp desc" )
    elif self.request.get('new'):
	q = db.GqlQuery('SELECT * FROM CheckoutLog WHERE _type = :1 order by timestamp desc limit 500', 'new-order-notification')
    else:
      q = db.GqlQuery('SELECT * FROM CheckoutLog order by timestamp desc limit 100')
    if q: 
      results = q.fetch(100)
      for result in results:
        self.response.out.write('<b><a href="/list?google_order_number=')
        self.response.out.write(result.google_order_number)
        self.response.out.write('">')
        self.response.out.write(result.google_order_number)
        self.response.out.write('</a></b>')
        self.response.out.write(' , ')
        self.response.out.write(result.timestamp)
        self.response.out.write(' , ')
        self.response.out.write(result._type)
        self.response.out.write(' , ')
        self.response.out.write(result.new_financial_order_state)
        self.response.out.write(' , ')
        self.response.out.write(result.new_fulfillment_order_state)
        self.response.out.write(' , ')
        self.response.out.write(result.latest_charge_amount)
        self.response.out.write(' , ')
        self.response.out.write(result.latest_charge_amount_currency)
        self.response.out.write(' , ')
        self.response.out.write(result.buyer_shipping_address_contact_name)
        self.response.out.write(' , ')
        self.response.out.write(result.buyer_shipping_address_address1)
        self.response.out.write(' , ')
        self.response.out.write(result.buyer_shipping_address_address2)
        self.response.out.write(' , ')
        self.response.out.write(result.buyer_billing_address_city)
        self.response.out.write(' , ')
        self.response.out.write(result.buyer_billing_address_postal_code)
        self.response.out.write(' , ')
        self.response.out.write(result.buyer_billing_address_email)
        self.response.out.write(' , ')
        self.response.out.write(result.buyer_billing_address_region)
        self.response.out.write(' , ')
        self.response.out.write(result.shopping_cart_items_item_1_item_name)
        self.response.out.write(' , ')
        self.response.out.write(result.shopping_cart_items_item_1_item_description)
        self.response.out.write(' , ')
        self.response.out.write(result.shopping_cart_items_item_1_digital_content_description)
        self.response.out.write(' , ')


	if result.shopping_cart_items_item_1_digital_content_description:
          url = 'url'
          url = 'http://move.brooklynmarathon.com/showXXXentry/%s' % re.sub("^.*-","",result.shopping_cart_items_item_1_digital_content_description)
          eventtype = strip_tags(re.sub("-.*$","",re.sub("^.* tracking: ","",result.shopping_cart_items_item_1_digital_content_description)))
          url = re.sub("XXX",eventtype,url)
	  # self.response.out.write('<a href="http://move.brooklynmarathon.com/showclubentry/%s">Details</a>' % re.sub("^.*-","",result.shopping_cart_items_item_1_digital_content_description))
	  self.response.out.write('<a href="%s">Details</a>' % url)
        if self.request.get('html'):
	  if result.html:
            self.response.out.write(' , ')
	    self.response.out.write('<br/>%s<hr/>' % result.html)


	#self.response.out.write('XX%sYY' % re.sub("^.*-","",result.shopping_cart_items_item_1_digital_content_description))
        #self.response.out.write(' , ')
        #self.response.out.write(result.entity)
        self.response.out.write('<br/>')

        if self.request.get('debug'):
          for attr, value in result.__dict__.iteritems():
            self.response.out.write(attr)
            self.response.out.write(' = ')
            self.response.out.write(value)
            self.response.out.write('<br/>')
          self.response.out.write('<hr/>')
    self.response.out.write('</body></html>')


class MainPage(webapp.RequestHandler):
  def get(self):
     self.redirect('/enqueuemail')
     #path = os.path.join(os.path.dirname(__file__), 'index.html')
     #self.response.out.write(template.render(path, {}))


  #  @require_admin  # DOES NOT WORK but needed
  def post(self):
     path = os.path.join(os.path.dirname(__file__), 'index.html')
     self.response.out.write(template.render(path, {}))

class MainPage1(webapp.RequestHandler):
  def get(self):
    greetings_query = Greeting.all().order('-date')
    greetings = greetings_query.fetch(10)

    if users.get_current_user():
      url = users.create_logout_url(self.request.uri)
      url_linktext = 'Logout'
    else:
      url = users.create_login_url(self.request.uri)
      url_linktext = 'Login'

    template_values = {
      'greetings': greetings,
      'url': url,
      'url_linktext': url_linktext,
      }

    path = os.path.join(os.path.dirname(__file__), 'index.html')
    self.response.out.write(template.render(path, template_values))

  def post(self):
    print self.request


def main():
  application = webapp.WSGIApplication(
                                       [
					   ('/', MainPage),
					   ('/list', List),
					   ('/send', Send),
					   ('/send_checkout', SendCheckout),
					   ('/dumptest', DumpTest),
      (r'/mail', MailHandler),
      (r'/enqueuemail', EnQueuePrimerMailHandler),
      (r'/enqueuemailadmin', EnQueuePrimerAdminMailHandler),
      (r'/worker/email', MailWorker),
      (r'/mail/hourly', HourlyMailHandler),
                                        ('/signup', Guestbook)],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
  main()


